package com.clwl.supervise.superviseapp.service.base;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.clwl.supervise.superviseapp.entity.base.TcCompany;
import com.clwl.supervise.superviseapp.entity.customer.DlBertAnswer;
import com.clwl.supervise.superviseapp.entity.customer.DlDataLabelTable;
import com.clwl.supervise.superviseapp.entity.customer.JgCustomerHotMsg;
import com.clwl.supervise.superviseapp.entity.customer.TsCustomerService;
import com.clwl.supervise.superviseapp.entity.risk.JgDynamicContent;
import com.clwl.supervise.superviseapp.entity.risk.JgDynamicScoring;
import com.clwl.supervise.superviseapp.entity.risk.JgDynamicStandard;
import com.clwl.supervise.superviseapp.entity.supervise.JgCheckContent;
import com.clwl.supervise.superviseapp.entity.supervise.JgStandard;
import com.clwl.supervise.superviseapp.entity.supervise.JgTemplate;
import com.clwl.supervise.superviseapp.mapper.base.SysConfigMapper;
import com.clwl.supervise.superviseapp.mapper.base.TcCompanyMapper;
import com.clwl.supervise.superviseapp.mapper.base.TsUserMapper;
import com.clwl.supervise.superviseapp.mapper.customer.*;
import com.clwl.supervise.superviseapp.mapper.risk.JgDynamicContentMapper;
import com.clwl.supervise.superviseapp.mapper.risk.JgDynamicScoringMapper;
import com.clwl.supervise.superviseapp.mapper.risk.JgDynamicStandardMapper;
import com.clwl.supervise.superviseapp.mapper.supervise.*;
import com.clwl.supervise.superviseapp.util.*;
import com.clwl.supervise.superviseapp.util.baiduAPI.BaiduAipUtil;
import com.clwl.supervise.superviseapp.util.bigdata.BigDataUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.sql.Clob;
import java.sql.SQLException;
import java.util.*;

@Service
@Slf4j
public class CustomerServiceService {

    @Resource
    private TsCustomerServiceMapper customerServiceMapper;
    @Resource
    private DlDataLabelTableMapper dlDataLabelTableMapper;
    @Resource
    private DlBertAnswerMapper dlBertAnswerMapper;
    @Resource
    private TableQueryMapper tableQueryMapper;
    @Resource
    private JgCustomerHotMsgMapper customerHotMsgMapper;
    @Resource
    private JgDynamicScoringMapper dynamicScoringMapper;
    @Resource
    private JgDynamicStandardMapper dynamicStandardMapper;
    @Resource
    private JgDynamicContentMapper dynamicContentMapper;
    @Resource
    private JgDailyStandardMapper jgDailyStandardMapper;
    @Resource
    private JgDailyContentMapper jgDailyContentMapper;
    @Resource
    private TcCompanyMapper companyMapper;
    @Resource
    private JgCheckMissingMapper jgCheckMissingMapper;
    @Resource
    private JgCheckProblemMapper jgCheckProblemMapper;
    @Resource
    private JgTemplateMapper templateMapper;
    @Resource
    private TsUserMapper tsUserMapper;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private RedisUtil redisUtil;


    /**
     * 发送消息得到回复
     *
     * @param message 消息内容
     * @return
     */
    public List<TsCustomerService> sendMessage(String message, Integer pageNum, Integer pageSize) {
        log.info("消息发送内容{}", message);
        //纯使用数据库数据分析
        return getCustomerServiceOld(message, pageNum, pageSize);
        //bert方式获取问题结果
        //return getCustomerServiceBert(message,pageNum ,pageSize);
    }


    /**
     * 通过标签获取结果信息
     *
     * @return 匹配到的问题列表
     */
    @DS("dss")
    public List<Map<String, String>> getQueryTableListByBart(String message, List<BigDataUtil.Semantics> messageList) {
        List<Map<String, String>> tableList = new ArrayList<>();
        log.info("messageList:" + messageList);
        // List<Map<String, String>> taggingList = new ArrayList<>();
        List<String> classList = new ArrayList<>();
//        classList.add(message );
        for (BigDataUtil.Semantics result : messageList) {
            classList.add(result.getValue());
        }
        //获取标注信息食品
        List<DlDataLabelTable> taggingChildrenList = dlDataLabelTableMapper.selectByLable(classList);
        for (DlDataLabelTable tsTaggingTable : taggingChildrenList) {
            Map<String, String> tableMap = new HashMap<>();
            tableMap.put("tableName", tsTaggingTable.getTable());
            tableMap.put("queryLabel", tsTaggingTable.getQueryLabel());
            tableList.add(tableMap);
         /*   //英文表名
            String tableEnName = tsTaggingTable.getTable();
            //获取表的字段名
            QueryWrapper<TsTaggingTableCl> tsTaggingTableClQueryWrapper = new QueryWrapper<>();
            tsTaggingTableClQueryWrapper.eq("TABLE_ID", tsTaggingTable.getId());
            List<TsTaggingTableCl> tsTaggingTableClList = tsTaggingTableClMapper.selectList(tsTaggingTableClQueryWrapper);
            List<String> queryColumnList = new ArrayList<>();
            String returnContentName = "";
            String returnTitleName = "";
            for (TsTaggingTableCl tsTaggingTableCl : tsTaggingTableClList) {
                if (StringUtils.equals("0", tsTaggingTableCl.getColumnType())) {
                    queryColumnList.add(tsTaggingTableCl.getNameEn());
                } else if (StringUtils.equals("1", tsTaggingTableCl.getColumnType())) {
                    returnContentName = tsTaggingTableCl.getNameEn().toUpperCase();
                } else if (StringUtils.equals("2", tsTaggingTableCl.getColumnType())) {
                    returnTitleName = tsTaggingTableCl.getNameEn().toUpperCase();
                }
            }
            //通过查询出来的表数据,查询表信息来对应的字段进行模糊查询
            List<Map<String, Object>> contentResult = tsTaggingTableMapper.selectInfoByTable(tableEnName, queryColumnList, tsTaggingTable.getTaggingName());
            for (Map<String, Object> contentr : contentResult) {
                Map<String, String> re = new HashMap<>();
                log.info("返回字段标题：" + returnTitleName);
                if (returnTitleName.length() < 0 || contentr.get(returnTitleName) == null) {
                    continue;
                }
                re.put("title", contentr.get(returnTitleName) + "");
                re.put("tableName", tableEnName);
                re.put("tableId", contentr.get("ID") + "");
                re.put("returnTitleName", returnTitleName);
                re.put("returnContentName", returnContentName);
                taggingList.add(re);
            }*/
        }
        return tableList;
        //去重复
     /*   Stream<Map<String, String>> disresultList = taggingList.stream().distinct();
        List<Map<String, String>> result = disresultList.collect(Collectors.toList());
        List<TsCustomerService> customerServicesList = new ArrayList<>();
        for (Map<String, String> s : result) {
            TsCustomerService customerService = new TsCustomerService();
            customerService.setCreateTime(new Date());
            customerService.setProblemAbstract(s.get("title"));
            customerService.setReturnTitleName(s.get("returnTitleName"));
            customerService.setReturnContentName(s.get("returnContentName"));
            customerService.setProblemTable(s.get("tableName"));
            customerService.setTableId(s.get("tableId"));
            customerService.setId(Long.valueOf(s.get("tableId")));
            customerServicesList.add(customerService);
        }
        //返回分页信息
        List<TsCustomerService> customerServicesPage = new ArrayList<>();
        customerServicesPage = getPage(pageNum,  customerServicesList, pageSize);
        return customerServicesPage;*/
    }

    @DS("dss")
    public List<Map<String, String>> getQueryTableListByBartN(List<BigDataUtil.Semantics> messageList) {
        List<Map<String, String>> tableList = new ArrayList<>();
        log.info("messageList:" + messageList);
        // List<Map<String, String>> taggingList = new ArrayList<>();
        List<String> classList = new ArrayList<>();
//        classList.add(message );
        for (BigDataUtil.Semantics result : messageList) {
            classList.add(result.getValue());
        }
        //获取标注信息食品
        List<String> taggingChildrenList = dlDataLabelTableMapper.selectByLableN(classList);
        for (String tsTaggingTable : taggingChildrenList) {
            Map<String, String> tableMap = new HashMap<>();
            tableMap.put("tableName", "xzcf_doc");
            tableMap.put("queryLabel", tsTaggingTable);
            tableList.add(tableMap);
        }
        return tableList;

    }


    @DS("ads")
    public List<TsCustomerService> getMessageResult(String message, List<Map<String, String>> tableNameList, Integer pageNum, Integer pageSize) {
        List<TsCustomerService> customerServicesList = new ArrayList<>();
        if (tableNameList.size() <= 0) {
            return customerServicesList;
        }
        List<Map<String, Object>> resultList = tableQueryMapper.selectMessageResult(pageNum, pageSize * pageNum, tableNameList, message);
        for (Map<String, Object> s : resultList) {
            TsCustomerService customerService = new TsCustomerService();
            customerService.setCreateTime(new Date());
            customerService.setProblemAbstract(s.get("ggmc") + "");
            customerService.setReturnTitleName("ggmc");
            customerService.setProblemResult(s.get("content") + "");
            customerService.setProblemAbstract(s.get("ggmc") + "");
            customerService.setReturnContentName(s.get("content") + "");
            customerService.setProblemTable(s.get("table_name") + "");
            customerService.setTableId(s.get("id") + "");
            customerService.setId(Long.valueOf(s.get("id") + ""));
            customerServicesList.add(customerService);
        }
        return customerServicesList;
    }

    /**
     * 纯使用数据库数据分析(在大数据未完全能用之前，演示使用)
     *
     * @param message 消息内容
     * @return
     */
    private List<TsCustomerService> getCustomerServiceOld(String message, Integer pageNum, Integer pageSize) {
        //根据发送的消息检索类似的问题进返回答案
        QueryWrapper queryWrapper2 = new QueryWrapper();
        queryWrapper2.eq("delete_flag", "0");
        queryWrapper2.orderByDesc("send_count");
        List<TsCustomerService> problemResultList = customerServiceMapper.selectList(queryWrapper2);

        List<TsCustomerService> resultList = new ArrayList<>();
        for (TsCustomerService customerService : problemResultList) {
            //判断关键字
            if (customerService.getKeywords() == null) {
                //如果没有关键字，直接通过标题筛选
                float suitability = getSimilarityRatio(customerService.getProblemResult(), message.trim());
                //相似度大一百分之二十
                if (suitability > 20) {
                    resultList.add(customerService);
                }
            } else {
//                判断关键字是否包含
                String[] keywords = customerService.getKeywords().split(";");
                List<String> keywordsList = Arrays.asList(keywords);
                for (String key : keywordsList) {
                    if (message.trim().contains(key)) {
                        resultList.add(customerService);
                    }
                }
            }
        }

        for (TsCustomerService customerService : problemResultList) {
            //如果没有关键字，直接通过标题筛选
            float suitability = getSimilarityRatio(customerService.getProblemAbstract(), message.trim());
            //相似度大一百分之二十
            if (suitability > 20) {
                resultList.add(customerService);
            }
        }

        //修改发送次数,反正以后也不用
        for (TsCustomerService tsCustomerService : resultList) {
            tsCustomerService.setSendCount(tsCustomerService.getSendCount() == null ? 1 : tsCustomerService.getSendCount() + 1);
            tsCustomerService.setProblemTable("TS_CUSTOMER_SERVICE");
            tsCustomerService.setReturnTitleName("PROBLEM_ABSTRACT");
            tsCustomerService.setReturnContentName("PROBLEM_RESULT");
            tsCustomerService.setProblemTable("TS_CUSTOMER_SERVICE");
            customerServiceMapper.updateById(tsCustomerService);
        }
        //返回分页信息
        List<TsCustomerService> customerServicesPage = getPage(pageNum, resultList, pageSize);
        return customerServicesPage;
    }


    /**
     * 用户语音转文字
     *
     * @param file
     * @return
     */
    public String audioToText(MultipartFile file) {
        String fileUrl = null;
        try {
            fileUrl = BaiduAipUtil.updateSpotImage(file);
        } catch (Exception e) {
            throw new RuntimeException("获取语音文件失败");
        }
        String text = BaiduAipUtil.getVoiceString(fileUrl);
        try {
            //识别完成删除文件
            BaiduAipUtil.deleteSpotImage(fileUrl);
        } catch (Exception e) {
            log.error("删除语音识别文件失败了!");
        }
        System.out.println("语音识别结果:" + text);
        return text;
    }


    /**
     * 获取消息详细信息
     *
     * @param messageId         消息Id
     * @param tableName         表名
     * @param titleColumnName   标题字段名
     * @param contentColumnName 内容字段名
     * @return
     */
    public Map<String, Object> getMessageDetail(Long messageId, String tableName, String titleColumnName, String contentColumnName) throws SQLException, IOException {
        Map<String, Object> contentResult = tableQueryMapper.selectContentByTable(messageId, tableName);
        log.info("contentResult:title-{},content-{}", contentResult.get("TITLE_INFO"), contentResult.get("CONTENT_INFO"));
        contentResult.put("CONTENT_INFO", ProjectStringUtils.clobToString((Clob) contentResult.get("CONTENT_INFO")));
        return contentResult;
    }

    /**
     * 获取相关功能提问最多的前五条
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    public IPage<JgCustomerHotMsg> getHotMessageList(Integer pageNum, Integer pageSize, String msgTitle) {
        //纯使用数据库数据分析
        QueryWrapper<JgCustomerHotMsg> customerHotMsgQueryWrapper = new QueryWrapper<>();
        customerHotMsgQueryWrapper.eq("delete_flag", "0");
        customerHotMsgQueryWrapper.eq("MSG_STATUS", "0");
        if (StringUtils.isNotEmpty(msgTitle)) {
            customerHotMsgQueryWrapper.like("MSG_TITLE", msgTitle);
        }
        customerHotMsgQueryWrapper.orderBy(true, false, "MSG_SEND_COUNT").orderBy(true, true, "ID");
        IPage<JgCustomerHotMsg> page = new Page<>(pageNum, pageSize);
        return customerHotMsgMapper.selectPage(page, customerHotMsgQueryWrapper);
    }

    /**
     * 对list进行分页返回
     *
     * @param pageNum              当前页数
     * @param customerServicesList 要分页的list
     * @param pageSize             每页数量
     * @return
     */
    private static List<TsCustomerService> getPage(Integer pageNum, List<TsCustomerService> customerServicesList, Integer pageSize) {
        List<TsCustomerService> customerServicesPage;
        if (pageNum == 0 || pageNum == 1) {
            customerServicesPage = customerServicesList.subList(0, Math.min(pageSize, customerServicesList.size()));
        } else {
            customerServicesPage = customerServicesList.subList(Math.min(((pageNum - 1) * pageSize), customerServicesList.size()),
                    Math.min(pageNum * pageSize, customerServicesList.size()));
        }
        return customerServicesPage;
    }


    /**
     * bert获取标签
     *
     * @param message
     * @return
     */
    public List<BigDataUtil.Semantics> getBertLabelList(String message) {
        return BigDataUtil.bert2Search(message);
    }


    /**
     * 通过用户选择的机器学习返回的标签查询 DlBertAnswer表对应 标签的数据
     *
     * @param label
     * @return
     */
    @DS("dss")
    public List<DlBertAnswer> bertLabelGetAnswerLabel(String label) {
        //将用户选择的标签提取出里面的许可证号
        //提取出天津市蓟州区安凤杰农家院、JY21200250058443中的JY21200250058443
        String licenseNumber = label.replaceAll(".*、", ""); //将许可证号提取出来
        //将licenseNumber放入到redis中
        redisUtil.set("licenseNumber", licenseNumber);
        return dlBertAnswerMapper.selectAnswerLabel(label);
    }


    @DS("dss")
    public List<DlDataLabelTable> answerLabelGetComment(String label) {
        return dlDataLabelTableMapper.selectByLableNew(label);
    }

    @DS("dss")
    public List<Map<String, Object>> commentGetLabel(String commentId) {
        DlDataLabelTable dataLabelTable = dlDataLabelTableMapper.selectById(Long.parseLong(commentId));
        String label = dataLabelTable.getLabel();
        List<String> labelList = Arrays.asList(label.split(","));
        List<Map<String, Object>> resultLabelList = new ArrayList<>();
        for (String labelName : labelList) {
            Map<String, Object> resultLabelMap = new HashMap<>();
            resultLabelMap.put("table", dataLabelTable.getTable());
            resultLabelMap.put("label", labelName);
            resultLabelMap.put("type", "0");
            resultLabelList.add(resultLabelMap);
        }
        return resultLabelList;
    }

    /**
     * 智能客服新流程-生产环境对接
     *
     * @param tableNameList
     * @param pageNum
     * @param pageSize
     * @return
     */
    @DS("ads")
    public List<TsCustomerService> getMessageResultNew(String tableName, String label, Integer pageNum, Integer pageSize, String companyId) {
        List<TsCustomerService> customerServicesList = new ArrayList<>();
        int start = pageNum * pageSize;
        start = start == 0 ? 0 : start + 1;
        int end = (pageNum + 1) * pageSize;
        tableName = tableName.toLowerCase();
        if (StringUtils.equals("null", companyId)) {
            companyId = null;
        }
        String licenseNumber = "null";
        //判断tableName是否是jg_rectification,jg_investigation,tc_company,jg_daily_check四个表中的一个
        List<String> superviseTableList = Arrays.asList("jg_rectification", "jg_investigation", "tc_company", "jg_daily_check");
        if (superviseTableList.contains(tableName)) {
            //取出之前存储的
            licenseNumber = redisUtil.get("licenseNumber");
        }
        List<Map<String, Object>> resultList = tableQueryMapper.selectMessageResultNew(start, end, tableName, label, companyId, licenseNumber);
        for (Map<String, Object> s : resultList) {
            TsCustomerService customerService = new TsCustomerService();
            customerService.setCreateTime(new Date());
            customerService.setReturnTitleName("ggmc");//返回信息标题的字段名
            customerService.setProblemResult(s.get("content") == null ? s.get("CONTENT") + "" : s.get("content") + "");
            customerService.setProblemAbstract(s.get("ggmc") == null ? s.get("GGMC") == null ? customerService.getProblemResult() : s.get("GGMC") + "" : s.get("ggmc") + "");
            customerService.setReturnContentName("content");//返回content信息的字段名
            customerService.setProblemTable(s.get("table_name") == null ? s.get("TABLE_NAME") + "" : s.get("table_name") + ""); //表名
            customerService.setTableId(s.get("id") == null ? s.get("ID") + "" : s.get("id") + "");
            customerService.setDetailType(s.get("detail_type") == null ? s.get("DETAIL_TYPE") + "" : s.get("detail_type") + "");
            customerService.setSendMessage(label);
            customerService.setType("0");
            customerServicesList.add(customerService);
        }
        return customerServicesList;
    }

    /**
     * 热门消息点击次数增加
     *
     * @return
     */
    public void addHotMessageViewNum(Long messageId) {
        //同步处理消息点击次数加一
        synchronized (messageId) {
            JgCustomerHotMsg jgCustomerHotMsg = customerHotMsgMapper.selectById(messageId);
            jgCustomerHotMsg.setMsgSendCount(jgCustomerHotMsg.getMsgSendCount() + 1);
            customerHotMsgMapper.updateById(jgCustomerHotMsg);
        }
    }

    /**
     * 通过Langchain发送知识库消息获取返回信息
     *
     * @param message
     */
    public ChatServiceResult sendLangChain(String message, String historyMessage) {
        //发送http请求, 将message传递给Langchain
        ChatProperties chatProperties = SpringUtil.getBean(ChatProperties.class);
        String chatDevPath = StringUtils.equals(chatProperties.getChatDevActive(), "dev") ? chatProperties.getChatDevPath() : StrUtil.blankToDefault(SpringUtil.getBean(SysConfigMapper.class).queryByKey(chatProperties.CHAT_PATH_KEY).getParamValue(), chatProperties.getChatDevPath());
        JSONObject queryParams = new JSONObject();
        queryParams.put("query", message);
        queryParams.put("knowledge_base_name", "samples");
        queryParams.put("top_k", "3");
        queryParams.put("score_threshold", "1");
        queryParams.put("stream", false);
        queryParams.put("model_name", "Qwen1.5-4B-Chat");
        queryParams.put("temperature", "0.7");
        queryParams.put("max_tokens", "0");
        queryParams.put("prompt_name", "default");
/*        if(StringUtils.isNotEmpty(historyMessage)) {
            JSONArray jsonArray = JSONArray.parseArray(historyMessage);
            queryParams.put("history", jsonArray);
        }*/
        log.info("chat地址:{}", chatDevPath + "/chat/knowledge_base_chat");
        String result = HttpUtil.createPost(chatDevPath + "/chat/knowledge_base_chat")
                .header("accept", "application/json")
                .header("Content-Type", "application/json")
                .body(queryParams.toJSONString())
                .timeout(30000)
                .execute().body();

        try {
            if (result == null || result.length() < 5) {
                log.info("chat返回信息:{}", result);
                return null;
            }
            log.info("chat返回信息:{}", result.substring(5));
            boolean jsonValid = JSONObject.isValid(result.substring(5));//判断是否是json格式
            log.info("是否为json格式数据:{}", jsonValid);
            if (!jsonValid) {
                return null;
            }
            JSONObject resultData = JSONObject.parseObject(result.substring(5));
            log.info("转换完成的json数据:{}", resultData);
            ChatServiceResult chatServiceResult = new ChatServiceResult();
            String answer = resultData.getString("answer") == null ? "" : resultData.getString("answer");
            chatServiceResult.setMessage(StringUtils.isEmpty(answer) ? "点击查看案例信息" : answer);
            JSONArray docs = resultData.getJSONArray("docs");
            if (docs == null || docs.size() == 0) {
                return chatServiceResult;
            }
            List<String> docList = new ArrayList<>();
            for (int i = 0; i < docs.size(); i++) {
                if (docs.getString(i).contains("未找到相关文档")) {
                    continue;
                }
                docList.add(docs.getString(i));
            }
            chatServiceResult.setKnowledgeBaseList(docList);
            return chatServiceResult;
        } catch (Exception e) {
            log.error("chat返回信息解析失败:{}", e);
            return null;
        }

    }


    /**
     * 判断两个字符串相似度
     *
     * @param str
     * @param target
     * @return
     */
    public static float getSimilarityRatio(String str, String target) {
        int d[][]; // 矩阵
        int n = str.length();
        int m = target.length();
        int i; // 遍历str的
        int j; // 遍历target的
        char ch1; // str的
        char ch2; // target的
        int temp; // 记录相同字符,在某个矩阵位置值的增量,不是0就是1
        if (n == 0 || m == 0) {
            return 0;
        }
        d = new int[n + 1][m + 1];
        for (i = 0; i <= n; i++) { // 初始化第一列
            d[i][0] = i;
        }
        for (j = 0; j <= m; j++) { // 初始化第一行
            d[0][j] = j;
        }
        for (i = 1; i <= n; i++) { // 遍历str
            ch1 = str.charAt(i - 1);
            for (j = 1; j <= m; j++) {
                ch2 = target.charAt(j - 1);
                if (ch1 == ch2 || ch1 == ch2 + 32 || ch1 + 32 == ch2) {
                    temp = 0;
                } else {
                    temp = 1;
                }
                d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + temp);
            }
        }
        return (1 - (float) d[n][m] / Math.max(str.length(), target.length())) * 100F;
    }


    public List<JgDynamicScoring> selectProblemList() {
        return dynamicScoringMapper.selectProblemList();
    }


    public TcCompany selectCompanyById(Long companyId) {
        return companyMapper.selectById(companyId);
    }

    @Transactional(rollbackFor = Exception.class)
    public void createDynamicScoring(JgDynamicScoring dynamicScoring, TcCompany company) {
        JgTemplate template = templateMapper.selectBySupProcess(company.getSupProcess(), company.getCompanyTypeId(), "3");
        dynamicScoring.setCompanyId(company.getId());
        dynamicScoring.setCompanyName(company.getCompanyName());
        dynamicScoring.setCreditCode(company.getCreditCode());
        dynamicScoring.setLicense(company.getLicense());
        dynamicScoring.setTemplateId(template.getId());
        dynamicScoring.setScoreYear(DateUtil.format(new Date(), "yyyy"));
        dynamicScoring.setManageStatus("0");
        dynamicScoring.setDelayRating("1");
        dynamicScoring.setScoreTotal(0D);
        dynamicScoring.setScoreTime(DateUtil.format(new Date(), "yyyy-MM-dd"));
        dynamicScoring.setDeleteFlag(0L);
        dynamicScoring.setCheckResults("合格");
        dynamicScoring.setCopeResult("1");
        dynamicScoring.setDescription("--");
        dynamicScoringMapper.insert(dynamicScoring);


        //检查结果-重点项数量
        Long importentCount = 0L;
        //检查结果-重点项序号
        List<String> importentOrders = new ArrayList<>();
        //检查结果-一般项数量
        Long generalCount = 0L;
        //检查结果-一般项序号
        List<String> generalOrders = new ArrayList<>();
        List<JgStandard> checkStandardList = jgDailyStandardMapper.selectDynamicStandardEntityList(company.getSupProcess(), company.getCompanyTypeId(), null);
        for (JgStandard checkStandard : checkStandardList) {
            JgDynamicStandard standard = new JgDynamicStandard();
            // 填充公共字段
            BeanUtils.copyProperties(checkStandard, standard, "id"); // 使用BeanUtils简化字段复制
            standard.setDynamicScoringId(dynamicScoring.getId());
            standard.setStandardId(checkStandard.getId());
            standard.setCreateTime(dynamicScoring.getCreateTime());
            standard.setCreatorId(dynamicScoring.getCreatorId());
            standard.setCreator(dynamicScoring.getCreator());
            standard.setCreateDeptId(dynamicScoring.getCreateDeptId());
            standard.setCreateDeptName(dynamicScoring.getCreateDeptName());
            standard.setTemplateId(template.getId());
            standard.setDeleteFlag(0L);
            standard.setSupCategory("3");
            standard.setSupProcess(company.getSupProcess());
            if(StringUtils.equals(company.getSupProcess(),"cyfw")){
                standard.setCyfwId(company.getCompanyTypeId());
            }
            if(StringUtils.equals(company.getSupProcess(),"spxs")){
                standard.setSpxsId(company.getCompanyTypeId());
            }
            dynamicStandardMapper.insert(standard); // 需配置返回主键
            //获取标准中检查内容TEPLATE_STANDARD_ID
            List<JgCheckContent> contentList = jgDailyContentMapper.selectDynamicEntityByStandardId(checkStandard.getTeplateStandardId(), null);
            for (JgCheckContent content : contentList) {
                JgDynamicContent dynamicContent = new JgDynamicContent();
                BeanUtils.copyProperties(content, dynamicContent, "id");
                dynamicContent.setContentId(content.getId());
                dynamicContent.setDynamicStandardId(standard.getId());
                if ("1".equals(content.getImportentItem())) {
                    //一般项
                    generalCount = generalCount + 1;
                    generalOrders.add(content.getSerialNum() == null ? "" : content.getSerialNum().toString());
                } else if ("2".equals(content.getImportentItem())) {
                    //一般项
                    importentCount = importentCount + 1;
                    importentOrders.add(content.getSerialNum() == null ? "" : content.getSerialNum().toString());
                }
                // 收集保存操作

                dynamicContent.setCreateTime(dynamicScoring.getCreateTime());
                dynamicContent.setCreatorId(dynamicScoring.getCreatorId());
                dynamicContent.setCreator(dynamicScoring.getCreator());
                dynamicContent.setCreateDeptId(dynamicScoring.getCreateDeptId());
                dynamicContent.setCreateDeptName(dynamicScoring.getCreateDeptName());
                dynamicContent.setDeleteFlag(0L);
                dynamicContent.setSelection("1");
                dynamicContentMapper.insert(dynamicContent);
            }
        }
        dynamicScoring.setImportentCount(importentCount);
        dynamicScoring.setImportentOrders(String.join(",", importentOrders));
        dynamicScoring.setGeneralCount(generalCount);
        dynamicScoring.setGeneralOrders(String.join(",", generalOrders));
        dynamicScoringMapper.updateById(dynamicScoring);

    }


}
